package club.xiaojiawei.array;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 2022/4/21 21:56
 * @question 54.螺旋矩阵
 * @description 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 */
public class SpiralMatrixI54 {

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        List<Integer> integers = spiralOrder(matrix);
        for (int i = 0; i < integers.size(); i++) {
            System.out.print(integers.get(i) + "\t");
        }
    }

    /**
     * 按层模拟
     * @param matrix
     * @return
     */
    public static List<Integer> spiralOrder(int[][] matrix) {
        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1, count = 0, amount = (bottom + 1) * (right + 1);
        List<Integer> list = new ArrayList<>(amount);
        while (true){
            for (int i = left; i <= right; i++){
                list.add(matrix[top][i]);
                count++;
            }
            if (count == amount){
                break;
            }
            top++;
            for (int i= top; i <= bottom; i++){
                list.add(matrix[i][right]);
                count++;
            }
            if (count == amount){
                break;
            }
            right--;
            for (int i = right; i >= left; i--){
                list.add(matrix[bottom][i]);
                count++;
            }
            if (count == amount){
                break;
            }
            bottom--;
            for (int i = bottom; i >= top; i--){
                list.add(matrix[i][left]);
                count++;
            }
            if (count == amount){
                break;
            }
            left++;
        }
        return list;
    }
}
